<template>
  <div class="bigBox">
    <el-row :gutter="10">
      <el-col :xs="24" :sm="14">
        <div class="app-container pd">
          <div class="filter-container">
            <el-input v-model="queryParams.roleName" class="filter-item search-item" />
            <el-button class="filter-item" type="primary" @click="search">
              查询
            </el-button>
            <el-button class="filter-item mr" type="success" @click="reset">
              重置
            </el-button>
            <el-dropdown trigger="click" class="filter-item">
              <el-button>
                更多操作<i class="el-icon-arrow-down el-icon--right" />
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item @click.native="add">新 增</el-dropdown-item>
                <el-dropdown-item @click.native="batchDelete">删 除</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
          <el-table
            ref="table"
            :key="tableKey"
            v-loading="loading"
            :data="list"
            border
            fit
            style="width: 100%;"
            @selection-change="onSelectChange"
            @sort-change="sortChange"
          >
            <el-table-column type="selection" align="center" width="40px" />
            <el-table-column label="角色名称" prop="username" :show-overflow-tooltip="true" align="center" min-width="100px">
              <template slot-scope="scope">
                <span>{{ scope.row.roleName }}</span>
              </template>
            </el-table-column>
            <el-table-column label="描述" prop="remark" :show-overflow-tooltip="true" align="center" min-width="200px">
              <template slot-scope="scope">
                <span>{{ scope.row.remark }}</span>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" prop="createTime" :show-overflow-tooltip="true" align="center" min-width="180px" sortable="custom">
              <template slot-scope="scope">
                <span>{{ scope.row.createTime }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="150px" class-name="small-padding fixed-width">
              <template slot-scope="{row}">
                <i class="el-icon-setting table-operation" style="color: #2db7f5;" @click="edit(row)" />
                <i class="el-icon-delete table-operation" style="color: #f50;" @click="singleDelete(row)" />
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-col>
      <el-col :xs="24" :sm="10">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>{{ role.roleId === '' ? '新增' : '修改' }}</span>
          </div>
          <div>
            <el-form ref="form" :model="role" :rules="rules" label-position="right" label-width="100px">
              <el-form-item label="角色名称" prop="roleName">
                <el-input v-model="role.roleName" :readonly="role.roleId === '' ? false : 'readonly'" />
              </el-form-item>
              <el-form-item label="是否为注册默认角色" prop="remark">
                <el-switch
                  v-model="role.defaultRole"
                  active-color="#13ce66"
                  :active-value="1"
                  :inactive-value="0"
                  inactive-color="#ff4949"
                />
              </el-form-item>
              <el-form-item label="描述" prop="remark">
                <el-input v-model="role.remark" type="textarea" rows="3" />
              </el-form-item>
              <el-form-item label="权限" prop="remark">
                <el-tree
                  ref="permsTree"
                  :data="permsTree"
                  :props="defaultProps"
                  :check-strictly="true"
                  show-checkbox
                  default-expand-all
                  accordion
                  node-key="id"
                  highlight-current
                />
              </el-form-item>
            </el-form>
          </div>
        </el-card>
        <el-card class="box-card">
          <el-row>
            <el-col :span="24" style="text-align: right">
              <el-button type="primary" :loading="buttonLoading" plain @click="submit">{{ role.roleId === '' ? '新增' : '修改' }}</el-button>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>
<script>

export default {
  name: 'RoleManage',
  data() {
    return {
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      tableKey: 0,
      loading: false,
      buttonLoading: false,
      list: null,
      selection: [],
      total: 0,
      permsTree: [],
      queryParams: {},
      sort: {},
      role: this.initRole(),
      rules: {
        roleName: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.fetch()
    this.initMenuTree()
  },
  methods: {
    initRole() {
      return {
        roleId: '',
        roleName: '',
        remark: ''
      }
    },
    initMenuTree() {
      this.$get('/user/route/list').then((r) => {
        this.permsTree = r.data.data
      })
    },
    onSelectChange(selection) {
      this.selection = selection
    },
    clearSelections() {
      this.$refs.table.clearSelection()
    },
    edit(row) {
      this.$refs.form.clearValidate()
      this.role = { ...row }
      if (this.role.role) {
        this.$refs.permsTree.setCheckedKeys(this.role.role.split(','))
      } else {
        this.$refs.permsTree.setCheckedKeys([])
      }
    },
    singleDelete(row) {
      this.$refs.table.toggleRowSelection(row, true)
      this.batchDelete()
    },
    batchDelete() {
      if (!this.selection.length) {
        this.$message({
          message: '请选择需要删除的项',
          type: 'warning'
        })
        return
      }
      this.$confirm('选中数据将被永久删除, 是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const roleIds = []
        this.selection.forEach((r) => {
          roleIds.push(r._id)
        })
        this.delete(roleIds)
      }).catch(() => {
        this.clearSelections()
      })
    },
    delete(roleIds) {
      this.loading = true
      const arr = roleIds.join(',')
      this.$delete(`/user/role/delete`, { ids: arr }).then(res => {
        this.$message({
          message: res.data.message,
          type: 'success'
        })
        this.search()
      })
    },
    submit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.buttonLoading = true
          if (this.role._id) {
            this.role.role = this.$refs.permsTree.getCheckedKeys().join(',')
            this.role.createTime = this.role.modifyTime = null
            this.$put('/user/role/update', { ...this.role }).then(res => {
              this.buttonLoading = false
              this.$message({
                message: res.data.message,
                type: 'success'
              })
              this.reset()
            })
          } else {
            this.role.role = this.$refs.permsTree.getCheckedKeys().join(',')
            this.$post('/user/role/add', { ...this.role }).then(res => {
              this.buttonLoading = false
              this.$message({
                message: res.data.message,
                type: 'success'
              })
              this.reset()
            })
          }
        } else {
          return false
        }
      })
    },
    add() {
      this.resetForm()
    },
    sortChange(val) {
      this.sort.field = val.prop
      this.sort.order = val.order
      this.search()
    },
    reset() {
      this.resetForm()
      this.queryParams = {}
      this.sort = {}
      this.$refs.table.clearSort()
      this.search()
    },
    resetForm() {
      this.$refs.form.clearValidate()
      this.$refs.form.resetFields()
      this.role = this.initRole()
      this.$refs.permsTree.setCheckedKeys([])
    },
    search() {
      this.resetForm()
      this.fetch({
        ...this.queryParams,
        ...this.sort
      })
    },
    fetch(params = {}) {
      this.loading = true
      this.$get('/user/role/list', { ...params }).then((r) => {
        this.list = r.data.data
        this.loading = false
      }).catch(_ => {
        this.loading = false
      })
    }
  }
}
</script>
<style lang="less" scoped>
    .role {
        margin: 10px;
        .app-container {
            margin: 0 0 10px 0 !important;
        }
    }
    .el-card.is-always-shadow {
        box-shadow: none;
    }
    .el-card {
        border-radius: 0;
        border: none;
        .el-card__header {
            padding: 10px 20px !important;
            border-bottom: 1px solid #f1f1f1 !important;
        }
    }

</style>
